<?php
class Debug
{
    private $handle = null;
    private $path   = "";
    private $isOpen = false;

    public function __construct( $path )
    {
        date_default_timezone_set('Europe/London');
        $this->path = $path;
        $this->open(); // touch the file
        $this->writeLine("... Log file started ...");
        $this->close();
    }
    
    public function __destruct()
    {
        $this->writeLine("... Log file finished ...\n", true, false);
        $this->close();
    }
    
    private function close()
    {
        if ($this->isOpen)
        {
            fclose($this->handle);
        }
        $this->isOpen = false;
    }
    
    private function open()
    {
        if ($this->isOpen)
        {
            $this->close();
        }

        if (! is_file($this->path))
        {
            fopen($this->path, 'w');
            chmod($this->path, 0600);
        }
        
        $this->handle = fopen($this->path, "a");
        $this->isOpen   = true;
    }
    
    public function writeLine($contents, $time = true, $close = true)
    {
        if (! $this->isOpen)
        {
            $this->open();
        }
        if ($time)
        {
            $contents = date("D jS M [G:i:s] -- ") . $contents;
        }
        $contents .= "\n";
        
        fwrite($this->handle, $contents);

        if ($close === true)
            $this->close();
    }
}
?>